import { boot } from 'quasar/wrappers'
import axios from 'axios'
import { useUserStore } from "src/stores/user";
import { Notify } from 'quasar'
// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)

const api = axios.create({ baseURL: process.env.API, withCredentials: false, timeout: 5000 })

// request interceptor
api.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (userStore.token) {

      config.headers['authorization'] = 'JWT ' + userStore.getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log('request:', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
api.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    if (error.response.status === 500) {
      Notify.create({
        message: error.response.statusText,
        icon: "announcement",
        color: "red",
        position: 'center',
      })
    } else {
      Notify.create({
        message: error.response.data.message,
        icon: "announcement",
        color: "red",
        position: 'center',
      })
    }


    return Promise.reject(error)
  }
)

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})

export { api }
